package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmalDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：lintao
 * @date ：Created in 2020/11/28
 * @description ：套餐业务层接口实现类
 * @version: 1.0
 */
@Service
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmalDao setmalDao;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmalDao.add(setmeal);
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            // 绑定套餐与检查组的多对多关系
            setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        }
        // 将图片名称保存到Redis
        savePic2Redis(setmeal.getImg());
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page =  setmalDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Setmeal> findAll() {
        return setmalDao.findAll();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmalDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmalDao.findSetmealCount();
    }

    private void savePic2Redis(String pic){
        Jedis jedis = jedisPool.getResource();
        jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,pic);
        jedis.close();
    }

    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        for (Integer checkgroupId : checkgroupIds) {
            Map<String,Integer> map = new HashMap<String, Integer>();
            map.put("setmealId",id);
            map.put("checkgroupId",checkgroupId);
            setmalDao.setSetmealAndCheckGroup(map);
        }
    }
}
